import React from 'react';
import {Row, Col, Icon, Input, Select, Form, Button, Checkbox, Radio, DatePicker} from 'antd';
import Utils from './utils';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

const {MonthPicker, RangePicker, WeekPicker} = DatePicker;

const initFormList = props => {
  const {getFieldDecorator} = props.form;
  const searchFieldList = props.searchFieldList;
  const expand = props.expand;
  const formItemList = [];
  const buttonList = [];
  const formLayout = {
    labelCol: {
      xs: {span: 5},
      sm: {span: 4},
    },
    wrapperCol: {
      xs: {span: 18, offset: 0.5},
      sm: {span: 19},
    },
  };

  const radioLayout = {
    labelCol: {
      // xs: { span: 2.5 },
      sm: {span: 2},
    },
    wrapperCol: {
      // xs: { span: 22 },
      sm: {span: 22},
    },
  };

  if (searchFieldList && searchFieldList.length > 0) {
    searchFieldList.forEach((item, i) => {
      let label = item.label;
      let field = item.field;
      let initialValue = item.initialValue || undefined;
      let placeholder = item.placeholder || '';
      let width = item.width || '';
      let attr = item.attr || {};
      if (item.type == 'INPUT') {
        const INPUT = (
          <Col span={8}>
            <FormItem
              label={label}
              key={field}
              {...attr}
              style={{width: '100%'}}
              labelAlign="right"
              {...formLayout}
            >
              {getFieldDecorator(field, {
                initialValue,
              })(<Input type="text" placeholder={placeholder}/>)}
            </FormItem>
          </Col>
        );
        formItemList.push(INPUT);
      } else if (item.type == 'SELECT') {
        const onChange = item.onChange || '';
        const SELECT = (
          <Col span={8}>
            <FormItem
              label={label}
              key={field}
              {...attr}
              style={{width: '100%'}}
              labelAlign="right"
              {...formLayout}
            >
              {getFieldDecorator(field, {
                initialValue: initialValue,
              })(
                <Select
                  allowClear
                  showSearch
                  placeholder={placeholder}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={onChange}
                >
                  {Utils.getOptionList(item.list)}
                </Select>,
              )}
            </FormItem>
          </Col>
        );
        formItemList.push(SELECT);
      } else if (item.type == 'AUTOSELECT') {
        const onChange = item.onChange || '';
        const onSearch = item.onSearch || '';
        const AUTOSELECT = (
          <Col span={8}>
            <FormItem
              label={label}
              key={field}
              {...attr}
              style={{width: '100%'}}
              {...formLayout}
            >
              {getFieldDecorator(field, {
                initialValue: initialValue,
              })(
                <Select
                  allowClear
                  showSearch
                  autoFocus
                  placeholder={placeholder}
                  defaultActiveFirstOption={false}
                  showArrow={false}
                  filterOption={false}
                  onSearch={onSearch}
                  onChange={onChange}
                  notFoundContent={null}
                >
                  {Utils.getOptionList(item.list)}
                </Select>,
              )}
            </FormItem>
          </Col>
        );
        formItemList.push(AUTOSELECT);
      } else if (item.type == 'TIMERANGE') {
        let format = item.format == undefined ? 'YYYY-MM-DD' : item.format;
        if (field && !Array.isArray(field)) {
          field = field.split(field.match(/\w+(\W+)\w+/)[1]);
        }
        const begin_time = (
          <FormItem label={item.label || '搜索时间范围'} key={field} labelAlign="right">
            {getFieldDecorator(field[0] || 'begin_time')(
              <DatePicker showTime={true} placeholder={placeholder} format={format}/>,
            )}
          </FormItem>
        );
        formItemList.push(begin_time);
        const end_time = (
          <FormItem label="~" colon={false} key={field + 1}>
            {getFieldDecorator(field[1] || 'end_time')(
              <DatePicker showTime={true} placeholder={placeholder} format={format}/>,
            )}
          </FormItem>
        );
        formItemList.push(end_time);
      } else if (item.type == 'RANGEPICKER') {
        let format = item.format == undefined ? 'YYYY-MM-DD' : item.format;
        const RANGEPICKER = (
          <Col span={8}>
            <FormItem
              label={label || '时间范围'}
              style={{width: '100%'}}
              labelAlign="right"
              {...formLayout}
            >
              {getFieldDecorator('range-picker', {
                rules: [
                  {
                    required: false,
                  },
                ],
                initialValue: '',
              })(
                <RangePicker
                  placeholder={placeholder ? placeholder : ['开始时间', '结束时间']}
                  format={format}
                />,
              )}
            </FormItem>
          </Col>
        );
        formItemList.push(RANGEPICKER);
      } else if (item.type == 'CHECKBOX') {
        const CHECKBOX = (
          <Col span={8}>
            <FormItem label={label} key={field} {...attr}>
              {getFieldDecorator([field], {
                valuePropName: field,
                initialValue: initialValue, //true | false
              })(<Checkbox>{label}</Checkbox>)}
            </FormItem>
            ;
          </Col>
        );
        formItemList.push(CHECKBOX);
      } else if (item.type == 'RADIO') {
        let RADIO = (
          <Col span={16}>
            <FormItem
              label={label}
              key={field}
              {...attr}
              style={{width: '100%'}}
              labelAlign="right"
              {...radioLayout}
            >
              {getFieldDecorator([field], {
                valuePropName: field,
                initialValue: initialValue, //true | false
              })(<RadioGroup>{Utils.getRadioList(item.list)}</RadioGroup>)}
            </FormItem>
          </Col>
        );

        formItemList.push(RADIO);
      } else if (item.type == 'BUTTON') {
        let callback = item.callback;
        let type = item.type;
        let icon = item.icon;
        let attr = item.attr || {};
        let value = item.label || item.value || item.field;
        let style = item.style || {marginLeft: '5px', marginTop: '3px'};
        if (field == '查询') {
          let icon = item.icon || 'search';
          var BUTTON = (
            <Button
              type="primary"
              icon={icon}
              style={style}
              {...attr}
              key={value}
              onClick={() => {
                if (!callback) {
                  const fieldsValue = props.form.getFieldsValue();
                  const rangeValue = fieldsValue['range-picker'];
                  if (rangeValue && rangeValue[0]) {
                    fieldsValue['beginTime'] = rangeValue[0].format('YYYY-MM-DD');
                    fieldsValue['endTime'] = rangeValue[1].format('YYYY-MM-DD');
                  }

                  delete fieldsValue['range-picker'];
                  props[field]({...fieldsValue});
                } else if (callback && props[callback.name]) {
                  props[callback.name](props.form.getFieldsValue());
                }
              }}
            >
              {value}
            </Button>
          );
        } else if (field == '重置') {
          let icon = item.icon || '';
          var BUTTON = (
            <Button
              icon="undo"
              style={style}
              {...attr}
              key={value}
              onClick={() => {
                props.form.resetFields();
                if (!callback) {
                  const fieldsValue = props.form.getFieldsValue();
                  const rangeValue = fieldsValue['range-picker'];
                  if (rangeValue && rangeValue[0]) {
                    fieldsValue['startTime'] = rangeValue[0].format('YYYY-MM-DD');
                    fieldsValue['endTime'] = rangeValue[1].format('YYYY-MM-DD');
                  }

                  delete fieldsValue['range-picker'];
                  props[field]({...fieldsValue});
                } else if (callback && props[callback.name]) {
                  props[callback.name](props.form.getFieldsValue());
                }
              }}
            >
              {value}
            </Button>
          );
        } else {
          var BUTTON = (
            <Button
              type={type}
              icon={icon}
              style={style}
              {...attr}
              key={value}
              onClick={() => {
                if (!callback) {
                  props[field](props.form.getFieldsValue());
                } else if (callback && props[callback.name]) {
                  props[callback.name](props.form.getFieldsValue());
                }
              }}
            >
              {value}
            </Button>
          );
        }
        if (item.power) {
          BUTTON = (
            <div style={{display: 'none'}} data-right={item.power}>
              BUTTON
            </div>
          );
        }
        buttonList.push(BUTTON);
      }
    });
  }

  buttonList.push(
    <Button
      type="primary"
      icon="search"
      key="search"
      style={{marginLeft: '5px', marginTop: '3px'}}
      onClick={() => {
        const fieldsValue = props.form.getFieldsValue();
        const rangeValue = fieldsValue['range-picker'];
        if (rangeValue && rangeValue[0]) {
          fieldsValue['startTime'] = rangeValue[0].format('YYYY-MM-DD');
          fieldsValue['endTime'] = rangeValue[1].format('YYYY-MM-DD');
        }
        delete fieldsValue['range-picker'];
        props['search']({...fieldsValue});
      }}
    >
      查看
    </Button>,
    <Button
      type=""
      // icon="undo"
      key="reset"
      style={{marginLeft: '5px', marginTop: '3px'}}
      onClick={() => {
        props.form.resetFields();
        const fieldsValue = props.form.getFieldsValue();
        const rangeValue = fieldsValue['range-picker'];
        if (rangeValue && rangeValue[0]) {
          fieldsValue['startTime'] = rangeValue[0].format('YYYY-MM-DD');
          fieldsValue['endTime'] = rangeValue[1].format('YYYY-MM-DD');
        }
        delete fieldsValue['range-picker'];
        props['reset']({...fieldsValue});
      }}
    >
      重置
    </Button>,
    props.searchNum > 10 ? (
      <span>
                <a style={{marginLeft: 8, fontSize: 14}} onClick={() => props['collapse'](!expand)}>
                    {expand ? '收起' : '展开'} <Icon type={expand ? 'up' : 'down'}/>
                    <div></div>
                </a>
            </span>
    ) : (
      ''
    ),
  );

  return formItemList.concat(buttonList);
};

const searchPageList = props => {
  const formLayout = {
    labelCol: {
      // xs: { span: 6 },
      sm: {span: 4},
    },
    wrapperCol: {
      // xs: { span: 18 },
      sm: {span: 16},
    },
  };

  return (
    <Form layout="inline" style={{marginBottom: 10}}>
      <Row>
        {initFormList(props)}
        {/* {console.log(initFormList(props))} */}
      </Row>
    </Form>
  );
};
export default Form.create({name: 'searchPageList'})(searchPageList);

//todo 'horizontal'|'vertical'|'inline'	'horizontal'
// todo kim-stamp colon={false} 可以去掉时间的  配合 label 属性使用，表示是否显示 label 后面的冒号
//todo kim-stamp  props.form.resetFields()重置
